<template>
  <div class="video-cut-editor">
    <h3>剪辑编辑器 - {{ video.fileName }}</h3>

    <!-- 视频预览区域 -->
    <div class="video-preview-container">
      <video
          ref="previewVideo"
          :src="videoPath + video.accessPath"
          @loadedmetadata="onVideoLoaded"
          @error="handleVideoError"
          class="non-interactive-video"
      ></video>

      <!-- 播放进度显示 -->
      <div class="progress-info">
        <span>{{ formatTime(timeSliderValues[0]) }} / {{ formatDuration(videoDuration) }}</span>
      </div>

      <!-- 时间选择滑块 -->
      <div class="time-slider">
        <div style="margin-bottom: 16px;">裁剪时间段：</div>
        <el-slider
            v-model="timeSliderValues"
            :min="0"
            :max="videoDuration"
            :step="0.001"
            range
            :format-tooltip="formatSliderTooltip"
            @change="handleSliderChange"
            style="margin-bottom: 16px;"
        />
        <div style="display: flex; gap: 16px; align-items: center; flex-wrap: wrap;">
          <span>开始时间：</span>
          <el-input :value="formatTime(timeSliderValues[0])" placeholder="HH:mm:ss.SSS" style="width: 150px;" readonly />
          <span>结束时间：</span>
          <el-input :value="formatTime(timeSliderValues[1])" placeholder="HH:mm:ss.SSS" style="width: 150px;" readonly />
        </div>
      </div>

      <!-- 生成按钮 -->
      <el-button
          type="primary"
          @click="generateVideo"
          :disabled="!canGenerate"
          class="generate-btn"
      >
        生成视频文件
      </el-button>
    </div>

    <!-- 裁剪结果弹窗 -->
    <el-dialog
        v-model="showResultDialog"
        title="裁剪结果预览"
        width="80%"
        @close="resetResult"
    >
      <div class="result-container">
        <video
            ref="resultVideo"
            :src="resultVideoSrc"
            controls
            class="result-video"
            @error="handleVideoError"
        ></video>
        
        <div class="result-actions">
          <el-button
              type="primary"
              @click="downloadResultVideo"
              :loading="downloading"
          >
            <el-icon><Download /></el-icon>
            下载视频文件
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { API_CONFIG } from "../api";
import { ElMessage } from "element-plus";
import videoDataAPI from "../api/modules/videoData";
import { Download } from '@element-plus/icons-vue';

const props = defineProps({
  video: {
    type: Object,
    required: true
  }
});

// DOM 引用
const previewVideo = ref(null);
const resultVideo = ref(null);

// 状态
const timeSliderValues = ref([0, 0]); // 存储起止时间的数组
const videoDuration = ref(0);
const hasChanged = ref(false);
const showResultDialog = ref(false);
const resultVideoSrc = ref('');
const downloading = ref(false);
const isProcessing = ref(false);
const videoPath = ref(API_CONFIG.IMAGE_URL);

// 计算属性
const canGenerate = computed(() => {
  return hasChanged.value && 
         timeSliderValues.value[0] < timeSliderValues.value[1] && 
         !isProcessing.value;
});

// 重置编辑器
const resetEditor = () => {
  timeSliderValues.value = [0, 0];
  hasChanged.value = false;
  showResultDialog.value = false;
  resultVideoSrc.value = '';
  
  if (previewVideo.value) {
    previewVideo.value.currentTime = 0;
  }
  
  // 尝试从props获取视频时长
  if (props.video?.duration) {
    videoDuration.value = props.video.duration;
    timeSliderValues.value = [0, props.video.duration];
  }
};

// 视频加载完成回调
const onVideoLoaded = () => {
  if (previewVideo.value) {
    videoDuration.value = previewVideo.value.duration || 10;
    timeSliderValues.value = [0, videoDuration.value];
    hasChanged.value = false;
  }
};

// 监听传入的视频数据变化
watch(() => props.video, (newVideo) => {
  if (newVideo) {
    resetEditor();
  }
}, { immediate: true });

// 格式化滑块tooltip显示
const formatSliderTooltip = (value) => {
  return formatTime(value);
};

// 滑块变化回调
const handleSliderChange = (values) => {
  hasChanged.value = true;
  // 实时同步视频播放时间到起始滑块位置
  if (previewVideo.value) {
    previewVideo.value.currentTime = values[0];
  }
  timeSliderValues.value = values;
};

// 更新当前时间
const updateCurrentTime = () => {
  // 此函数在当前实现中已不需要
};

// 生成视频
const generateVideo = async () => {
  if (!canGenerate.value) {
    ElMessage.warning('请先拖动滑块选择视频时间段');
    return;
  }
  
  isProcessing.value = true;
  try {
    // 创建新的随机三位数，确保文件名不重复
    const randomThreeDigit = Math.floor(Math.random() * 900) + 100;
    const uniqueFilename = `${props.video.fileNameWithoutSuffix}_剪辑${randomThreeDigit}`;
    
    // 计算裁剪时长（从起始时间到结束时间）
    const startTime = secondsToHMS(timeSliderValues.value[0]);
    const duration = secondsToHMS(timeSliderValues.value[1] - timeSliderValues.value[0]);
    
    const params = {
      inputPath: props.video.absolutePath,
      outputPath: `${uniqueFilename}.mp4`,
      startTime: startTime,
      duration: duration,
    };
    
    // 调用裁剪接口
    const result = await videoDataAPI.cutVideoData(params);
    
    if (result?.code === 0) {
      ElMessage.success('视频裁剪成功！');
      // 显示裁剪结果
      resultVideoSrc.value = videoPath.value + result.data;
      showResultDialog.value = true;
    } else {
      throw new Error(result?.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('视频剪辑失败:', error);
    ElMessage.error(`视频剪辑失败: ${error.message}`);
  } finally {
    isProcessing.value = false;
  }
};

// 下载裁剪后的视频
const downloadResultVideo = async () => {
  if (!resultVideoSrc.value) {
    ElMessage.warning('没有可下载的视频');
    return;
  }
  
  downloading.value = true;
  try {
    // 调用Electron API下载视频
    const result = await window.electronAPI.downloadVideo({
      url: resultVideoSrc.value,
      defaultFilename: `${props.video.fileNameWithoutSuffix}_剪辑`
    });
    
    if (result.success) {
      ElMessage.success(`视频已保存至:\n${result.path}`);
    } else {
      ElMessage.warning(result.message || '下载已取消');
    }
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error(`下载失败: ${error.message}`);
  } finally {
    downloading.value = false;
  }
};

// 重置结果
const resetResult = () => {
  resultVideoSrc.value = '';
  if (resultVideo.value) {
    resultVideo.value.pause();
  }
};

// 格式化时间（精确到毫秒）
const formatTime = (seconds) => {
  if (isNaN(seconds) || seconds < 0) return "00:00.000";
  
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  const ms = Math.floor((seconds % 1) * 1000);
  
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`;
};

// 格式化时长
const formatDuration = (seconds) => {
  if (isNaN(seconds) || seconds <= 0) return "00:00.000";
  
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  const ms = Math.floor((seconds % 1) * 1000);
  
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`;
};

// 秒转时分秒格式
const secondsToHMS = (seconds) => {
  // 取整秒数
  const totalSeconds = Math.floor(seconds);
  
  // 计算小时、分钟和剩余秒数
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const secs = totalSeconds % 60;
  
  // 格式化为两位数
  const pad = (num) => num.toString().padStart(2, '0');
  
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
};

// 视频错误处理
const handleVideoError = (event) => {
  const video = event.target;
  
  // 忽略空src属性的错误（这通常是在重置状态时故意设置的）
  if (!video.src || video.src === window.location.origin + '/') {
    return;
  }
  
  console.error("视频加载错误：", {
    src: video.src,
    errorCode: video.error.code,
    errorMsg: video.error.message
  });
  
  ElMessage.error(`视频加载失败: ${video.error.message || '未知错误'}`);
};

// 组件挂载
onMounted(() => {
  if (props.video?.duration) {
    videoDuration.value = props.video.duration;
  }
});

// 组件卸载
onUnmounted(() => {
  if (previewVideo.value) {
    previewVideo.value.pause();
  }
  if (resultVideo.value) {
    resultVideo.value.pause();
  }
});

// 暴露方法供父组件调用
defineExpose({
  reset: resetEditor
});
</script>

<style scoped>
.video-cut-editor {
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-top: 20px;
  background: #f9f9f9;
}

.video-preview-container {
  margin-bottom: 20px;
}

.non-interactive-video {
  width: 100%;
  max-height: 400px;
  background: #000;
  pointer-events: none;
}

.progress-info {
  text-align: center;
  margin: 10px 0;
  font-size: 14px;
  color: #666;
}

.time-slider {
  margin: 20px 0;
}

.slider-item {
  margin-bottom: 25px;
}

.slider-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.slider-item span {
  display: block;
  text-align: center;
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

.generate-btn {
  width: 100%;
  padding: 10px;
}

.result-container {
  text-align: center;
}

.result-video {
  width: 100%;
  max-height: 500px;
  background: #000;
  margin-bottom: 20px;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .non-interactive-video,
  .result-video {
    max-height: 300px;
  }
  
  .result-actions {
    flex-direction: column;
  }
  
  .result-actions button {
    width: 100%;
  }
  
  .time-slider > div {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .time-slider el-input {
    width: 100% !important;
    margin-bottom: 8px;
  }
}
</style>
